<?php

namespace App\Http\Controllers\Resources;

use App\Services\Statistics\BaseService;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Collection;
use PHPExcel;
use Helper;
use PHPExcel_Style_Alignment;
use PHPExcel_IOFactory;
use App\Services\Statistics\CompaniesFieldService;

class StatisticsController extends Controller
{
    /**
     * 初始化
     * MessagesController constructor.
     * @param BaseService $baseService
     */
    public function __construct(BaseService $baseService)
    {
        $this->_repoService = $baseService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        /**@var Collection $data *///这里生命$data是一个collection,这样下面的forpage就能找到源码
        $data = $this->_repoService->getCompaniesList();
        if (!empty($data)) {
            return $data;
        } else {
            return [];
        }
    }

    /**
     * 渠道报表导出excel文件
     */
    public function export()
    {
        $data = $this->_repoService->getCompaniesList();
        if (empty($data)) {
            return $this->_error('无数据，无法导出文件');
        }
        $dataWithState = $this->getStatus($data);
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '企业名称')
            ->setCellValue('C1', '开始时间')
            ->setCellValue('D1', '结束时间')
            ->setCellValue('E1', '状态')
            ->setCellValue('F1', '账号数量')
            ->setCellValue('G1', '微信总数')
            ->setCellValue('H1', '已用微信')
            ->setCellValue('I1', '未用微信号')
            ->setCellValue('J1', '好友数量')
            ->setCellValue('K1', '对话客户数')
            ->setCellValue('L1', '发送消息')
            ->setCellValue('M1', '好友消息')
            ->setCellValue('N1', '标签数量');
        $count = count($dataWithState) + 2;
        $totalData = $this->getTotalAccount($dataWithState);
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue("A$count", '统计')
            ->setCellValue("F$count", $totalData['accountCountTotal'])
            ->setCellValue("G$count", $totalData['wxClientCountTotal'])
            ->setCellValue("H$count", $totalData['projectCountTotal'])
            ->setCellValue("I$count", $totalData['unusedCountTotal'])
            ->setCellValue("J$count", $totalData['contactNumTotal'])
            ->setCellValue("K$count", $totalData['dialogueNumTotal'])
            ->setCellValue("L$count", $totalData['sendMsgCountTotal'])
            ->setCellValue("M$count", $totalData['getMsgCountTotal'])
            ->setCellValue("N$count", $totalData['tagCountTotal']);

        foreach ($dataWithState as $key => $value) {
            $num = $key + 2;
            $orderNum = $key + 1;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $num, $orderNum)
                ->setCellValue('B' . $num, $value->name)
                ->setCellValue('C' . $num, $value->startDate)
                ->setCellValue('D' . $num, $value->endDate)
                ->setCellValue('E' . $num, $value->state)
                ->setCellValue('F' . $num, $value->accountCount)
                ->setCellValue('G' . $num, $value->wxClientCount)
                ->setCellValue('H' . $num, $value->projectCount)
                ->setCellValue('I' . $num, $value->unusedCount)
                ->setCellValue('J' . $num, $value->contactNum)
                ->setCellValue('K' . $num, $value->dialogueNum)
                ->setCellValue('L' . $num, $value->sendMsgCount)
                ->setCellValue('M' . $num, $value->getMsgCount)
                ->setCellValue('N' . $num, $value->tagCount);
        }
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ->setHorizontal(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $title = 'reportForms' . time();
        $objPHPExcel->getActiveSheet()->setTitle('reportForm');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $title . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 获取总数相关数据
     */
    public function getTotalAccount($dataWithState)
    {
        foreach ($dataWithState as $key => $value) {
            $accountCountArr[] = $value->accountCount;//账号数量数据
            $wxClientCountArr[] = $value->wxClientCount;//微信总数数据
            $projectCountArr[] = $value->projectCount;//已用微信数据
            $unusedCountArr[] = $value->unusedCount;//未用微信数据
            $contactNumArr[] = $value->contactNum;//好友数量数据
            $dialogueNumArr[] = $value->dialogueNum;//对话客户数数据
            $sendMsgCountArr[] = $value->sendMsgCount;//发送消息数据
            $getMsgCountArr[] = $value->getMsgCount;//接受消息数据
            $tagCountArr[] = $value->tagCount;//标签数据
        }
        $arr = [
            'accountCountTotal' => array_sum($accountCountArr),
            'wxClientCountTotal' => array_sum($wxClientCountArr),
            'projectCountTotal' => array_sum($projectCountArr),
            'unusedCountTotal' => array_sum($unusedCountArr),
            'contactNumTotal' => array_sum($contactNumArr),
            'dialogueNumTotal' => array_sum($dialogueNumArr),
            'sendMsgCountTotal' => array_sum($sendMsgCountArr),
            'getMsgCountTotal' => array_sum($getMsgCountArr),
            'tagCountTotal' => array_sum($tagCountArr),
        ];
        return $arr;
    }

    /**
     * 获取账号状态
     */
    public function getStatus($data)
    {
        foreach ($data as $key => $value) {
            $startDatetime = '';
            $endDatetime = '';
            if (!empty($value->startDate)) {
                $startDatetime = strtotime($value->startDate);
            }
            if (!empty($value->endDate)) {
                $endDatetime = strtotime($value->endDate);
            }
            if (!empty($value->deleted_at)) {
                $state = '禁用';
            } else {
                if ($startDatetime > time()) {
                    $state = '未开始';
                }
                if ($endDatetime < time()) {
                    $state = '已到期';
                }
                if ($startDatetime < time() && time() < $endDatetime) {
                    $state = '正常使用';
                }
                if (is_null($value->startDate) && is_null($value->endDate)) {
                    $state = '永久使用';
                }
            }
            $data[$key]->state = $state;
        }
        return $data;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
